import 'package:bruno/bruno.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';

import '../../../../../app/routes/app_pages.dart';
import '../../../../data/models/get_consultation_res.dart';
import '../controllers/chat_page_controller.dart';

class ChatPageView extends GetView<ChatPageController> {
  const ChatPageView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xffF1F1F1),
        appBar: BrnAppBar(
          automaticallyImplyLeading: false,
          title: "我的问诊",
          backgroundColor: const Color(0xffF1F1F1),
          showDefaultBottom: false,
          backLeadCallback: () => Get.back(),
        ),
        body: Obx(() {
          return EasyRefresh(
            controller: controller.refreshController,
            header: const ClassicHeader(),
            footer: const ClassicFooter(),
            onLoad: controller.onLoad,
            onRefresh: controller.onRefresh,
            child: ListView.separated(
              itemCount: controller.list.length,
              itemBuilder: (context, index) {
                return _buildItem(controller.list[index]);
              },
              separatorBuilder: (context, index) {
                return const Divider(
                  height: 1,
                  color: Color(0xffE5E5E5),
                );
              },
            ),
          );
        }));
  }

  Widget _buildItem(ConsultationModel model) {
    return Container(
        constraints: BoxConstraints(
          minHeight: 60, // 设置最小高度避免动态计算问题
        ),
        child: GestureDetector(
          onTap: () {
            Get.toNamed(Routes.CHAT_DETAIL_PAGE, arguments: {
              "cid": model.id,
              "avatar": model.didAvatar,
              "receiverId": model.did,
              "receiverName": model.didName
            });
          },
          child: Stack(
            children: [
              Container(
                height: 72,
                width: double.infinity,
                padding: EdgeInsets.symmetric(horizontal: 16),
                color: Colors.white,
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        _buildAvatar(controller.isDoctor
                            ? model.pidAvatar ?? ""
                            : model.didAvatar ?? ''),
                        Text(
                          controller.isDoctor
                              ? model.pidName ?? ""
                              : model.didName ?? '',
                          style: TextStyle(
                            color: Color(0xff1f1f1f),
                            fontSize: 16,
                            fontWeight: FontWeight.w400,
                          ),
                        )
                      ],
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(formatTimestamp(model.latestMessageTime)),
                        SizedBox(
                          width: 4,
                        ),
                        Icon(
                          Icons.arrow_forward_ios_sharp,
                          color: Color(0xff1f1f1f),
                          size: 15,
                        )
                      ],
                    )
                  ],
                ),
              ),
              Positioned(
                left: 16 + 36 + 10,
                bottom: 8,
                child: Container(
                    width: 180,
                    child: Text(
                      model.latestMessageContent ?? '',
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                        fontSize: 14,
                      ),
                    )),
              )
            ],
          ),
        ));
  }

  Widget _buildAvatar(String avatarUrl) {
    return Container(
      height: 36,
      width: 36,
      margin: EdgeInsets.only(left: 4, right: 4, top: 4),
      child: CachedNetworkImage(
        imageUrl: avatarUrl,
        imageBuilder: (context, image) => CircleAvatar(
          foregroundImage: image,
          radius: 18,
        ),
        errorWidget: (context, url, error) => Container(
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.5),
            borderRadius: BorderRadius.circular(18),
          ),
        ),
        placeholder: (context, url) => Container(
          decoration: BoxDecoration(
            color: const Color(0xffF1F1F1),
            borderRadius: BorderRadius.circular(18),
          ),
        ),
      ),
    );
  }
}

String formatTimestamp(int? timestamp) {
  if (timestamp == null || timestamp == 0) {
    return "暂无记录";
  }
  DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
  String formattedDate =
      "${dateTime.year}/${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')}";
  String formattedTime =
      "${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}";
  return "$formattedDate $formattedTime";
}
